#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include "proc.h"

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[])
{
	FILE *fp = NULL;
	int len = 0, len_tmp = 0, dummy_bin = 0;
	unsigned char *rbuf = NULL;
	unsigned char *wbuf = NULL;
	unsigned char tmp[PATH_LEN];
	memset(&g_data, 0, sizeof(proc_data_t));
	//printf("argc:%d,argv[0]:%s\r\n", argc,(char *)argv[0]);
	strcpy(g_data.ini_path_name, (char *)argv[0]);

	g_data.ini_path_name[strlen(g_data.ini_path_name)-strlen(INI_NAME)] = 0;
	path_proc(g_data.ini_path_name);
	strcpy(g_data.ini_path_name, strcat(g_data.ini_path_name, argc == 2 ? (char *)argv[1] : INI_NAME));
	printf("INI:%s\r\n", g_data.ini_path_name);

	if(Read_Tnifile())
		return -1;
	for (int i = 0; i < g_data.bin_num; i++)
	{
		if(0 == memcmp("null", g_data.bin_in[i], 4))
		{
			//printf("@:%s\r\n", g_data.bin_in[i]);
			len_tmp = g_data.align_len[i] + g_data.pre_len[i];
			wbuf = (unsigned char *)malloc(len_tmp);
			memset(wbuf, g_data.fill_pat[i], len_tmp);
			printf("#%d alen:%#x plen:%#x in:%s out:%s\r\n", 
				i, g_data.align_len[i], g_data.pre_len[i], g_data.bin_in[i], g_data.bin_out[i]);
		}
		else
		{
			if ((fp = fopen(g_data.bin_in[i], "rb")) == NULL)
			{
				printf("#%d bin:%s read fail\r\n", i, g_data.bin_in[i]);
				continue;
			}
			else
			{
				printf("#%d alen:%#x plen:%#x in:%s out:%s\r\n", 
					i, g_data.align_len[i], g_data.pre_len[i], g_data.bin_in[i], g_data.bin_out[i]);
			}
			fseek(fp, 0, SEEK_END);
			len = ftell(fp);
			rewind(fp);
			rbuf = (unsigned char *)malloc(len);
			fseek(fp, 0, SEEK_SET);
			fread(rbuf, 1, len, fp);
			fclose(fp);
			if(g_data.align_len[i] > len)
			{
				len_tmp = g_data.align_len[i] + g_data.pre_len[i];
			}
			else
			{
				len_tmp = len + g_data.align_len[i] - (len%g_data.align_len[i]) + g_data.pre_len[i];
			}
			//len_tmp = ((g_data.align_len[i] > len) ? g_data.align_len[i] : len) + g_data.pre_len[i];
			//(len % g_data.align_len[i]) ? ((len & ~(g_data.align_len[i] - 1)) + g_data.align_len[i]) : len;
			//printf("#%d:alen:%#x,len:%#x,%#x,%#x,len_tmp:%#x\r\n", i, g_data.align_len[i], len, g_data.align_len[i]%len, len%g_data.align_len[i], len_tmp);
			wbuf = (unsigned char *)malloc(len_tmp);
			memset(wbuf, g_data.fill_pat[i], len_tmp);
			memcpy(wbuf + g_data.pre_len[i], rbuf, len);	
			free(rbuf);
		}
		fp = fopen(g_data.bin_out[i], "wb");
		fwrite(wbuf, 1, len_tmp, fp);
		fclose(fp);
		free(wbuf);
	}

	Write_Tnifile();
	return 0;
}
